// pages/home/category/uploadCTdata/orderpay/billinfo/billinfo.js
Component({
  properties: {
    modalHidden: {    //弹窗显示与隐藏
      type: Boolean,
      value: true
    },
    invoice: {
      type: Object,
      value: {
        type: 3,
        invoice_type: 1,
        invoice_title: '',
        taxpayer_code: '',
        address: {phone: '', email: ''},
        registered_address: '',
        registered_phone: '',
        bank_name: '',
        bank_account: '',
        taxpayers_certificate_id: '',  //增值税复印件
        business_license_id: '', //营业执照
        account_permit_id: ''   //开户许可
      }
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    isPersonal: 1,
    // isCommonBill: 1,
    currentFile: null,
    canClick: false,
    agree: false,
    uploadData: [
      { title: '增值税一般纳税人认定通知书复印件（加盖公章）', url: '', isChooseImg: false },
      { title: '营业执照复印件（加盖公章）', url: '', isChooseImg: false },
      { title: '开户许可证复印件(加盖公章)', url: '', isChooseImg: false }
    ],
    imageIndex:0,
    updateInvoice:{},
    haveInvoice:false,
    id:'',
    isEdit:false,
    taxpayer_code_tips:false,
    invoice:{
      type: 3,
      invoice_type: 1,
      invoice_title: '',
      taxpayer_code: '',
      address: {phone:'',email:''},
      registered_address: '',
      registered_phone: '',
      bank_name: '',
      bank_account: '',
      taxpayers_certificate_id: '',  //增值税复印件
      business_license_id: '', //营业执照
      account_permit_id: '' ,
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  created: function () {
    wx.eventBus.on('getInvoiceInfo',  (data)=> {
      console.log('子组建提交------', this.data.invoice)
      this.saveInvoices()
    })
    wx.eventBus.on('editInvoiceInfo',  (data)=> {
      var uploadDatas = this.data.uploadData
      var idobj = {
        0: data.taxpayers_certificate_id?wx.envConfig.orderListImgHost + data.taxpayers_certificate_id + '.img':'',
        1: data.business_license_id?wx.envConfig.orderListImgHost + data.business_license_id + '.img':'',
        2: data.account_permit_id?wx.envConfig.orderListImgHost + data.account_permit_id + '.img':'',
      }
      uploadDatas.forEach(function(item,index){
        item.isChooseImg = idobj[index]?true:false
        item.url = idobj[index]
      })
      // invoice.address = data.invoice_address
      this.setData({
        invoice:data,
        uploadData: uploadDatas,
        isEdit:true
      })
    })
    wx.eventBus.on('addInvoiceInfo', (data) => {
      var uploadDatas = this.data.uploadData
      var idobj = {
        0: '',
        1: '',
        2: '',
      }
      uploadDatas.forEach(function (item, index) {
        item.isChooseImg = false
        item.url = idobj[index]
      })
      this.setData({
        invoice: data,
        uploadData: uploadDatas,
        isEdit:false
      })
    })
    wx.eventBus.on('getInvoiceAddress', (data) => {
      let self = this
      let invoice = self.data.invoice
      invoice.address = wx.getStorageSync('address') ? wx.getStorageSync('address'):{}
      invoice.user_id = wx.getStorageSync('userInfo').id
      invoice.address_id = wx.getStorageSync('userInfo').address_id
      self.setData({
        invoice: invoice
      })
      // self.setData({
      //   invoice: data
      // })
    })
  },
  methods:{
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    // onReady: function () {

    // },

    /**
     * 生命周期函数--监听页面显示
     */
    // onShow: function () {
    //   let self = this
    //   let invoice = self.data.invoice
    //   invoice.address = wx.getStorageSync('address')
    //   invoice.user_id = wx.getStorageSync('userInfo').id
    //   invoice.address_id = wx.getStorageSync('userInfo').address_id
    //   self.setData({
    //     invoice: invoice
    //   })
    // },

    /**
     * 生命周期函数--监听页面隐藏
     */
    // onHide: function () {

    // },

    /**
     * 生命周期函数--监听页面卸载
     */
    // onUnload: function () {

    // },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    // onPullDownRefresh: function () {

    // },

    /**
     * 页面上拉触底事件的处理函数
     */
    // onReachBottom: function () {

    // },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function () {

    // },
    /**
     * 点击radio
     */
    choose: function (event) {
      let self = this
      var invoice = self.data.invoice
      invoice.invoice_type = event.currentTarget.dataset.choose
      self.setData({
        invoice: invoice
      })
    },
    /**
     * 点击发票类型选择按钮
     */
    billType: function (event) {
      let self = this
      var invoice = self.data.invoice
      invoice.type = JSON.parse(event.currentTarget.dataset.specialuse)
      self.setData({
        invoice: invoice,
      })
    },
    agreeConfirm:function(){
      this.setData({
        agree: !this.data.agree
      })
    },
    //同意资质
    agreeBill: function () {
      let self = this
      wx.showModal({
        title: '申请开具增值税专用发票确认书',
        content: '根据国家税法及发票管理相关规定，任何单位和个人不得要求他人为自己开具与实际经营业务情况不符的增值税专用发票。【包含并不限于\n（1）在没有货物采购或者没有接受应税务的情况下要求他人为自己开具增值税专用发票；\n<b>（2）</b>虽有货物采购或者接受应税务但要求他人为自己开具数量或金额与实际情况不符的增值税专用发票】，否则属于“虚开增值税专用发票”。我已经重复了解上述各项相关国家税法和发票管理规定，并确认仅就我司实际购买或服务索取发票。如我司未按国家相关规定申请开具或使用增值税专用发票，由我司自行承担相应法律后果否则',
        showCancel: false,
        confirmText: '我知道了',
        confirmColor: '#4825BF',
        success: function (res) {
          if (res.confirm) {
            self.setData({
              agree: true
            })
          }
        }
      })
    },
    //纳税人识别码说明
    taxpayerTips: function () {
      wx.eventBus.trigger('seeTaxpayer', true)
    },
    // 发票抬头
    invoiceTitle: function (e) {
      let self = this
      var invoice = self.data.invoice
      invoice.invoice_title = e.detail.value
      // self.setData({
      //   invoice: invoice
      // })
    },
    invoiceEmail: function (e) {
      let self = this
      var invoice = self.data.invoice
      invoice.address.email = e.detail.value
    },
    invoicePhone: function (e) {
      let self = this
      var invoice = self.data.invoice
      invoice.address.phone = e.detail.value
    },
    // 纳税人识别码
    taxpayerCode: function (e) {
      let self = this
      var invoice = self.data.invoice
      invoice.taxpayer_code = e.detail.value
      // self.setData({
      //   invoice: invoice
      // })
    },
    // 注册地址
    registeredAddress: function (e) {
      let self = this
      var invoice = self.data.invoice
      invoice.registered_address = e.detail.value
      // self.setData({
      //   invoice: invoice
      // })
    },
    // 注册电话
    registeredPhone: function (e) {
      let self = this
      var invoice = self.data.invoice
      invoice.registered_phone = e.detail.value
      // self.setData({
      //   invoice: invoice
      // })
    },
    // 开户银行
    bankName: function (e) {
      let self = this
      var invoice = self.data.invoice
      invoice.bank_name = e.detail.value
      // self.setData({
      //   invoice: invoice
      // })
    },
    // 银行账户
    bankAccount: function (e) {
      let self = this
      var invoice = self.data.invoice
      invoice.bank_account = e.detail.value
      // self.setData({
      //   invoice: invoice
      // })
    },
    /**
     * 上传图片
     */
    chooseImg: function (e) {
      let self = this
      console.log('data-currentIndex', e)
      self.setData({
        imageIndex: e.currentTarget.dataset.currentindex
      })
      // return
      wx.showActionSheet({
        itemList: ['照相', '从相册选择照片'],
        itemColor: '#4825BF',
        success: function (res) {
          console.log('res.tapIndex', res.tapIndex)
          self.chooseImgOrTakephoto(res.tapIndex, e.currentTarget.dataset.currentindex)
        },
        fail: function (res) {
          console.log(res.errMsg)
        }
      })
    },
    /**
     * 选择图片或照相
     */
    chooseImgOrTakephoto: function (tapIndex, imgIndex) {
      let self = this
      wx.showLoading({
        title: '',
      })
      let arr = []
      if (tapIndex === 0) {
        arr.push('camera')
      }
      if (tapIndex === 1) {
        arr.push('album')
      }
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original'], // 可以指定是原图(original)还是压缩图(compressed)，默认二者都有
        sourceType: arr, // 可以指定来源是相册还是相机，默认二者都有
        success: function (data) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = data.tempFilePaths[0]
          console.log('tempFilePaths', tempFilePaths)
          /*
           * TODO 修改上传相关的方式路径.............................................
           */
          wx.showLoading({
            title:'上传中...',
            mask:true
          })
          wx.uploadFile({
            url: wx.envConfig.filePath + 'file/uploadFile',
            filePath: tempFilePaths,
            name: 'file',
            formData: {
              fileTemp: JSON.stringify({ belongTo: "1" }),
              metadata: JSON.stringify([
                { name: "author", value: wx.getStorageSync('userInfo').userName },   //当前登录人的用户名(不是昵称)
                { name: "where", value: "miniProgram" },     //来自哪个端，端名自己定
                { name: "type", value: "img" },          //自己大概估一个类型
                { name: "remark", value: "发票证件照" }  //文件的业务逻辑(干嘛用的，大概的就行)
              ])
            },
            success: function (res) {
              res.data = JSON.parse(res.data)
              if (res.data.error_code == 'Y10000') {
                getApp().fileBinding(res.data.datas).then(ress => {
                  wx.hideLoading()
                  var uploadData = self.data.uploadData
                  var invoice = self.data.invoice
                  if (self.data.imageIndex == 0) {
                    uploadData[0].url = wx.envConfig.orderListImgHost + ress.data.datas.id + '.img'
                    invoice.taxpayers_certificate_id = ress.data.datas.id
                    uploadData[0].isChooseImg = true
                  }
                  else if (self.data.imageIndex == 1) {
                    uploadData[1].url = wx.envConfig.orderListImgHost + ress.data.datas.id + '.img'
                    invoice.business_license_id = ress.data.datas.id
                    uploadData[1].isChooseImg = true
                  }
                  else if (self.data.imageIndex == 2) {
                    uploadData[2].url = wx.envConfig.orderListImgHost + ress.data.datas.id + '.img'
                    invoice.account_permit_id = ress.data.datas.id
                    uploadData[2].isChooseImg = true
                  }
                  self.setData({
                    uploadData: uploadData,
                    invoice: invoice
                  })
                })

              }
            }
          })
        }
      })
    },

    // 订单详情
    getOrderDetail: function (id) {
      var self = this
      wx.showLoading({
        title: '正在加载...',
      })
      wx.request({
        url: wx.envConfig.host + '/order/findByOrder?params=' + JSON.stringify({ "order_id": id }) + '&cookiez=' + wx.getStorageSync('cookiez'),
        method: 'POST',
        success: function (res) {
          wx.hideLoading();
          if (res.data.error_code === "Y10000") {
            var updateInvoice = self.data.updateInvoice
            updateInvoice.order_id = self.data.id
            self.setData({
              updateInvoice: updateInvoice
            })
            if (res.data.datas.serviceInfo.invoiceInfo) {
              var invoice = res.data.datas.serviceInfo.invoiceInfo
              if (res.data.datas.serviceInfo.invoiceInfo.type == 2) {
                var uploadData = [
                  { title: '增值税一般纳税人认定通知书复印件（加盖公章）', url: '', isChooseImg: true },
                  { title: '营业执照复印件（加盖公章）', url: '', isChooseImg: true },
                  { title: '开户许可证复印件(加盖公章)', url: '', isChooseImg: true }
                ]
                res.data.datas.serviceInfo.invoiceInfo.address = JSON.parse(res.data.datas.serviceInfo.invoiceInfo.invoice_address)
                uploadData[0].url = wx.envConfig.orderListImgHost + invoice.taxpayers_certificate_id + '.img'
                uploadData[1].url = wx.envConfig.orderListImgHost + invoice.business_license_id + '.img'
                uploadData[2].url = wx.envConfig.orderListImgHost + invoice.account_permit_id + '.img'
                self.setData({
                  uploadData: uploadData
                })
              }
              invoice.address = JSON.parse(res.data.datas.serviceInfo.invoiceInfo.invoice_address)
              if (res.data.datas.serviceInfo.invoiceInfo.type == 2) {
                self.setData({
                  agree: true,
                })
              }
              self.setData({
                haveInvoice: true,
                invoice: invoice
              })
            }
          }
        },
        fail: function ({ errMsg }) {
          console.log('request fail', errMsg)
        }
      })
    },
    /**
     * 点击确定
     */
    finishClick: function () {
      // if (!this.data.canClick) {
      //   return
      // }
      this.saveInvoices(this.data.invoice)
    },
    // 提交发票信息
    saveInvoices: function (data) {
      var self = this
      var invoice = self.data.invoice
      invoice.invoice_address = JSON.stringify(self.data.invoice.address)
      self.setData({
        invoice: invoice
      })
      if (self.data.invoice.type === 3) { //发票抬头
        if (self.data.invoice.invoice_title === '') {
          wx.showToast({
            title: '请填写发票抬头',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.invoice_type == '2') {
          if (self.data.invoice.taxpayer_code === '') {
            wx.showToast({
              title: '请填写纳税人识别码',
              duration: 1000,
              mask: true
            })
            return
          }
        }
        if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(self.data.invoice.address.phone)) {
          wx.showToast({
            title: '请填写收票人手机号码',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (!/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(self.data.invoice.address.email)) {
          wx.showToast({
            title: '请填写正确的收票人邮箱',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
      }
      if (self.data.invoice.type === 2) { //发票抬头
        if (self.data.agree == 0) {
          wx.showToast({
            title: '请阅读赠票资质确认书,并同意',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.invoice_title === '') {
          wx.showToast({
            title: '请填写发票抬头',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.taxpayer_code === '') {
          wx.showToast({
            title: '请填写纳税人识别码',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.registered_address === '') {
          wx.showToast({
            title: '请填写注册地址',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (!self.data.invoice.registered_phone) {
          wx.showToast({
            title: '请填写正确的注册电话',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.bank_name === '') {
          wx.showToast({
            title: '请填写开户银行',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.bank_account === '') {
          wx.showToast({
            title: '请填写银行账户',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (!self.data.invoice.invoice_address) {
          wx.showToast({
            title: '请填写收票人信息',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.taxpayers_certificate_id == '') {
          wx.showToast({
            title: '请上传增值税一般纳税人认定通知书复印件照片',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.business_license_id == '') {
          wx.showToast({
            title: '请上传营业执照复印件照片',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
        if (self.data.invoice.account_permit_id == '') {
          wx.showToast({
            title: '请上传开户许可证复印件照片',
            icon: 'none',
            duration: 1000,
            mask: true
          })
          return
        }
      }
      if (!self.data.isEdit) {
        self.saveNewInvoice(self.data.invoice)
      } else {
        self.upDataInvoice(self.data.invoice)
      }
    },
    /**
     * 点击添加收货地址
     */
    addAddress: function () {
      console.log('跳转至收货地址', '1111')
      wx.navigateTo({
        url: '/pages/mine/personalInformation/deliveryAddress/deliveryAddress?type=edit',
      })
    },
    // 保存发票
    saveNewInvoice: function (data) {
      let self = this
      wx.request({
        url: wx.envConfig.host + '/invoice/save?params=' + JSON.stringify(data) + '&cookiez=' + wx.getStorageSync('cookiez'),
        method: 'POST',
        success: function (res) {
          if (res.data.error_code === "Y10000") {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 1000,
              mask: true
            })
            self.setData({
              modalHidden:true
            })
            wx.eventBus.trigger('findAllInvoiceList', true)
          }
        },
        fail: function ({ errMsg }) {
          console.log('request fail', errMsg)
        }
      })
    },
    //更新发票
    upDataInvoice: function (data) {
      let self = this
      wx.request({
        url: wx.envConfig.host + '/invoice/update?params=' + JSON.stringify(data) + '&cookiez=' + wx.getStorageSync('cookiez'),
        method: 'POST',
        success: function (res) {
          if (res.data.error_code === "Y10000") {
            wx.showToast({
              title: '发票信息提交成功',
              icon: 'succes',
              duration: 1000,
              mask: true
            })
            self.setData({
              modalHidden: true
            })
            wx.eventBus.trigger('findAllInvoiceList', true)
          }
        },
        fail: function ({ errMsg }) {
          console.log('request fail', errMsg)
        }
      })
    },
    closeModel: function () {
      this.setData({
        modalHidden: true
      })
    }
  }
 
})